<?php

/**
  * wechat php test
  */
//define your token

require("util.php");
require("config.php");
connect_db();

define("TOKEN", "bybakalan");
$wechat_obj = new wechat_callbackapi();
if (array_key_exists("echostr", $_GET))
	$wechat_obj->valid();
else
	$wechat_obj->response_msg(); 

class wechat_callbackapi{
	public function valid(){
        $echo_str = $_GET["echostr"];

        //valid signature , option
        if($this->check_signature()){
        	echo $echo_str;
        	exit;
        }
    }

    public function log_file($filename,$msg){
        //打开文件
        $fd = fopen($filename,"a");
        //增加文件
        $str = "[".date("Y/m/d h:i:s",time())."]".$msg;
        //写入字符串
        fwrite($fd, $str."\n\n");
        //关闭文件
        fclose($fd);
    }
     
    public function response_msg(){
		//get post data, May be due to the different environments
		$post_str = $GLOBALS["HTTP_RAW_POST_DATA"];
        $this->log_file("../logs/debug.log", $post_str);

      	//extract post data
		if (!empty($post_str)){
			$post_obj = simplexml_load_string($post_str, "SimpleXMLElement", LIBXML_NOCDATA);
			$from_username = $post_obj->FromUserName;
            $this->log_file("../logs/debug.log", $from_username);
			$to_username = $post_obj->ToUserName;
            $this->log_file("../logs/debug.log", $to_username);
            $MsgType = $post_obj->MsgType;

            $recieve_time = $post_obj->CreateTime;
            $this->log_file("../logs/debug.log", (string)$recieve_time);

            $recieve_datetime = date("Y-m-d H:i:s", (int)$recieve_time);
            //$recieve_datetime = date("Y-m-d H:i:s", "1");
            $this->log_file("../logs/debug.log", $recieve_datetime);

            if ($MsgType=="text") {
			    $message = trim($post_obj->Content);
                $msgid = $post_obj->MsgId;

                //$sql = sprintf("select type from response_type where text = '%s'", $message);
                $sql = sprintf('select title, description, pic_url, url from news where 
                                title like "%%%1$s%%" or lable like "%%%1$s%%" limit 1', $message);
                $ret = mysql_query($sql);
                if (!$ret) {
                    $response_type = "text";
                    $content_str = "感谢您对我们的关注
                                    发送“目录”查看故事列表
                                    发送“活动”查看有奖活动
                                    发送“我要讲故事”来给大家讲故事
                                    发送数字查看每篇故事
                                    =================
                                    如果喜欢我们的故事，戳右上角再戳右上角可以将美好的故事分享给您的好友，感谢您对我们的关注/爱心
                                    我们会一直努力为您的宝宝提供优质故事。
                                    希望您的宝宝健康成长";
                }
                else {
                    $response_type = 'news';
                    $row = mysql_fetch_assoc($ret);
                    $title = $row['title'];
                    $description = $row['description'];
                    $pic_url = $row['pic_url'];
                    $url = $row['url'];
                    
                    $sql = sprintf('select title, description, pic_url, url 
                                    from news where lable like "%%%1$s%%" limit 1', '吃奶');
                    $ret = mysql_query($sql);
                    $row = mysql_fetch_assoc($ret);
                    $pro_title = $row['title'];
                    $pro_description = $row['description'];
                    $pro_pic_url = $row['pic_url'];
                    $pro_url = $row['url'];
                }
            }

            else if ($MsgType=="event") {
                $response_type = "text";
                $event = $post_obj->Event;
                $event_key = $post_obj->EventKey;

                if ($event=="subscribe") {
                    sql_or_die(sprintf("insert into users (user_name, sub_time) values('%s', '%s')", $from_username, $recieve_datetime));
                    $msg_type = "text";
                    $content_str = "欢迎关注兰卡宝贝!

                    点击\"兰卡产品->益智游戏\"查看我们的儿童益智游戏

                    点击\"兰卡产品->儿童故事\"查看我们的有声故事绘本";
                }
                else if ($event=="unsubscribe") {
                    sql_or_die(sprintf("update users set unsub_time = '%s' where unsub_time is null", $recieve_datetime));
                    $content_str = "一个用户离开了我们";
                    $this->log_file("../logs/debug.log", $content_str);
                    return;
                }

                else if ($event=="CLICK") {
                    if ($event_key=="promocodes") {
                        $content_str = "完成注册，就可以获得兰卡宝贝app哦。
                        请回复您的微信号，输入格式为：\"注册+微信号\"。
                        例如微信号为\"aaa\"，
                        就发送\"注册aaa\"。";
                    }
                }

            }

			$time = time();
			$text_tpl = "<xml>
                             <ToUserName><![CDATA[%s]]></ToUserName>
                             <FromUserName><![CDATA[%s]]></FromUserName>
                             <CreateTime>%s</CreateTime>
                             <MsgType><![CDATA[%s]]></MsgType>
                             <Content><![CDATA[%s]]></Content>
                             <FuncFlag>0</FuncFlag>
                         </xml>";

            $news_tpl = "<xml>
                             <ToUserName><![CDATA[%s]]></ToUserName>
                             <FromUserName><![CDATA[%s]]></FromUserName>
                             <CreateTime>%s</CreateTime>
                             <MsgType><![CDATA[news]]></MsgType>
                             <ArticleCount>%s</ArticleCount>
                             <Articles>
                             %s
                             %s
                             </Articles>
                            </xml>"; 

            $each_item = "<item>
                             <Title><![CDATA[%s]]></Title> 
                             <Description><![CDATA[%s]]></Description>
                             <PicUrl><![CDATA[%s]]></PicUrl>
                             <Url><![CDATA[%s]]></Url>
                          </item>";

            if ($response_type == "text") {
                $this->log_file("../logs/debug.log", $content_str);
                $msg_type = "text";
                $result_str = sprintf($text_tpl, $from_username, $to_username, $time, $msg_type, $content_str);
                $this->log_file("../logs/debug.log", $result_str);
                echo $result_str;
                $this->log_file("../logs/debug.log", "echo finished\n");
            }
                
            else if ($response_type == "news") {
                $this->log_file("../logs/debug.log", "$title, $description");
                $response_news_tpl = sprintf($news_tpl, $from_username, $to_username, $time, 2, $each_item, $each_item);
                $response_news = sprintf($response_news_tpl, $title, $description, 
                                    $pic_url, $url, $pro_title, $pro_description, $pro_pic_url, $pro_url);
                $this->log_file("../logs/debug.log", "$response_news");
                echo $response_news;
            }

        }else{
        	echo "";
        	exit;
        }
    }
		
	private function check_signature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = TOKEN;
		$tmp_arr = array($token, $timestamp, $nonce);
		sort($tmp_arr);
		$tmp_str = implode( $tmp_arr );
		$tmp_str = sha1( $tmp_str );
		
		if( $tmp_str == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>
